<template>
  <div>
    <!-- 顶部面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            :options="cateList"
            :props="paramsProps"
            v-model="selectedKeys"
            @change="handleParamsChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many" :disabled="selectedKeys.length===3 ? false: true">
          <el-button
            type="primary"
            :disabled="selectedKeys.length===3 ? false: true"
            @click="showAddDialog"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyList" border stripe>
            <!-- 拓展行 -->
            <el-table-column type="expand">
              <!-- ！！！注意：这里一定要有一个<template></template> 用来接收数据 ！！！ -->
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeAttrTag(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDailog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性表格 -->
        <el-tab-pane label="静态属性" name="only" :disabled="selectedKeys.length===3 ? false: true">
          <el-button
            type="primary"
            :disabled="selectedKeys.length===3 ? false: true"
            @click="showAddDialog"
          >添加属性</el-button>
          <el-table :data="onlyList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeAttrTag(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDailog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数或者属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addAialogVisible"
      width="50%"
      @close="addFormClosed"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="editAialogVisible"
      width="50%"
      @close="editFormClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [],
      paramsProps: {
        // 鼠标进入显示二级选项
        expandTrigger: 'hover',
        value: 'cat_id',
        // 要展示的项
        label: 'cat_name',
        // 父子级嵌套关系
        children: 'children'
      },
      // 存储选中的各项分类id
      selectedKeys: [],
      // 当前激活的tab
      activeName: 'many',
      // 动态属性列表
      manyList: [],
      // 静态属性列表
      onlyList: [],
      // 添加对话框的显示与隐藏
      addAialogVisible: false,
      // 添加表单
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editForm: {
        attr_name: ''
      },
      editAialogVisible: false,
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('请求商品分类数据失败! ')
      }
      this.cateList = res.data
    },
    // 监听分类选中状态
    handleParamsChange() {
      this.getParamsList()
    },
    // 监听tab栏的改变
    handleTabClick() {
      this.getParamsList()
      console.log(this.activeName)
    },
    // 获取参数列表
    async getParamsList() {
      // 如果选中的不是三级分类 下面的参数表格不显示
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyList = []
        this.onlyList = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        // item.attr_vals.split(' ') ||
        // if(tem.attr_vals)

        /*  原字符串
            "49吋4K超薄曲面 人工智能,55吋4K观影曲面 30核HDR,55吋4K超薄曲面 人工智能,65吋4K超薄曲面 人工智能"
            , 分割
            0: "49吋4K超薄曲面 人工智能"
            1: "55吋4K观影曲面 30核HDR"
            2: "55吋4K超薄曲面 人工智能"
            3: "65吋4K超薄曲面 人工智能"
            ' ' 分割
            0: "49吋4K超薄曲面"
            1: "人工智能,55吋4K观影曲面"
            2: "30核HDR,55吋4K超薄曲面"
            3: "人工智能,65吋4K超薄曲面"
            4: "人工智能"
        */
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      // 先判断是请求的数据动态的还是静态的 载赋值
      if (this.activeName === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
    },
    showAddDialog() {
      this.addAialogVisible = true
    },
    addFormClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败！')
        }
        this.$message.success('添加参数成功')
        this.addAialogVisible = false
        this.getParamsList()
      })
    },
    // 显示修改对话框
    async showEditDailog(attrId) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      console.log(attrId)
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('查询参数失败！')
      }
      this.editForm = res.data
      this.editAialogVisible = true
    },
    // 关闭修改对话框 重置表单
    editFormClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定按钮 提交刚刚修改的参数名
    editParams() {
      this.$refs.editFormRef.validate(async vaild => {
        if (!vaild) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('修改参数失败！')
        }
        this.$message.success('修改参数成功')
        this.editAialogVisible = false
        this.getParamsList()
      })
    },
    // 删除参数
    async removeParams(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }
      this.getParamsList()
      this.$message.success('删除参数成功')
    },
    showInput(row) {
      row.inputVisible = true
      // $nextTick 方法只在页面渲染完成之后才触发
      this.$nextTick(_ => {
        // 让输入框默认聚集焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 保存添加的参数
    async saveAddAttrTags(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败！')
      }
      this.$message.success('修改参数成功！')
    },
    // 监听键盘按下 和 失去焦点 事件
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAddAttrTags(row)
    },
    // 监听tag 关闭事件
    removeAttrTag(i, row) {
      // 从数组中删除一个标签
      row.attr_vals.splice(i, 1)
      // 保存到数据库
      this.saveAddAttrTags(row)
    }
  },
  computed: {
    // 监听当前选中的商品分类的三级id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 监听对话框的title
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.cat-opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
